<template>
  <div>
    <el-form
      ref="formRef"
      :model="regForm"
      label-width="79.9992px"
      class="regForm"
      :rules="rules"
    >
      <el-form-item prop="username" label="用户名">
        <el-input v-model.trim="regForm.username" :prefix-icon="UserFilled" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input type="email" v-model="regForm.email" :prefix-icon="Eleme" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model.trim="regForm.password"
          :prefix-icon="Lock"
        />
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="isChecked" label="同意条款" />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          round
          @click="submitForm(formRef)"
          class="regBtn"
          auto-insert-space
          >注册</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { UserFilled, Lock, Eleme } from "@element-plus/icons-vue";
import { ElMessage, type FormInstance } from "element-plus";
import useStore from "@/store";
export type TregForm = { username: string; email: string; password: string };
let regForm = ref<TregForm>({
  username: "",
  email: "",
  password: "",
});
let isChecked = ref<boolean>(true);

const rules = ref({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 4, max: 16, message: "长度为4-16字", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: "格式不正确",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 32, message: "长度为6-32字", trigger: "blur" },
  ],
});

const formRef = ref<FormInstance>();
const emit = defineEmits(["setVisible"]);
const { user } = useStore();
const submitForm = (formRef: FormInstance | undefined) => {
  if (!isChecked.value) return ElMessage.warning("请勾选同意条款");
  formRef?.validate(async (valida) => {
    if (!valida) return;
    await user.registerUser(regForm.value);
    emit("setVisible");
  });
};
</script>

<style scoped lang="less">
.regForm {
  padding-right: 20px;
}
.regBtn {
  width: 100%;
}
</style>
